package com.gears_software.sxdc.dccx.ui.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.gears_software.sxdc.dccx.BuildConfig;
import com.gears_software.sxdc.dccx.R;
import com.gears_software.sxdc.dccx.application.DCCXApplication;
import com.gears_software.sxdc.dccx.data.finder.IBaseFinder;
import com.gears_software.sxdc.dccx.data.finder.util.GearsErrorHandler;
import com.gears_software.sxdc.dccx.data.model.ResultModel;
import com.gears_software.sxdc.dccx.data.model.AboutModel;
import com.gears_software.sxdc.dccx.data.model.VersionUpdateModel;
import com.sdsmdg.tastytoast.TastyToast;
import com.umeng.analytics.MobclickAgent;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.App;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.TextArrayRes;
import org.androidannotations.rest.spring.annotations.RestService;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import qiu.niorgai.StatusBarCompat;

/**
 * Created by chezhenzhen on 2017/8/25.
 */

@EActivity(R.layout.activity_about)
public class AboutActivity extends AppCompatActivity {

    @App
    DCCXApplication app;
    @ViewById
    TextView back_icon;
    @ViewById
    TextView right_icon;
    @ViewById
    TextView actionbar_title;
    @ViewById
    TextView txt_right_icon;
    @ViewById
    TextView txt_appname;
    @ViewById
    TextView txt_hotline;
    @ViewById
    TextView txt_address;
    @ViewById
    TextView txt_version;
    @ViewById
    TextView txt_version1;
    @ViewById
    TextView txt_zhichi_tel;
    @ViewById
    LinearLayout ly_bottom;
    @ViewById
    RelativeLayout re_version;
    @ViewById
    RelativeLayout re_hotline;
    @RestService
    IBaseFinder baseFinder;
    @Bean
    GearsErrorHandler errorHandler;
    String downUrl = "";
    ProgressDialog pBar;
    Context context;
    String phone = "";


    @AfterViews
    void created() {
        context = this;
        initIconFont();
        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(this, R.color.colorActionbar));
        baseFinder.setRestErrorHandler(errorHandler);
        txt_version.setText("v" + String.valueOf(BuildConfig.VERSION_NAME));
        txt_version1.setText(String.valueOf(BuildConfig.VERSION_NAME));
        getAbout();
    }

    void initIconFont() {
        actionbar_title.setText("关于我们");
        back_icon.setText(R.string.back_icon);
        back_icon.setTypeface(app.iconfont);
        right_icon.setVisibility(View.GONE);
        txt_right_icon.setTypeface(app.iconfont);
    }

    @Background
    void getAbout() {
        ResultModel<AboutModel> res = baseFinder.getAbout();
        showResult(res);
    }

    @UiThread
    void showResult(ResultModel<AboutModel> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                if (res.getData() != null) {
                    AboutModel aboutModel = res.getData();
                    phone = aboutModel.getFtel();
                    txt_appname.setText(aboutModel.getFname());
                    txt_hotline.setText(aboutModel.getFtel());
                    txt_address.setText(aboutModel.getFaddress());
                }
            }
        }
    }


    //版本更新
    @Click
    void re_version() {
        getVersionUpdate();
    }

    @Background
    void getVersionUpdate() {
        ResultModel<VersionUpdateModel> res = baseFinder.getVersion("2", "1");
        showVersionResult(res);
    }

    @UiThread
    void showVersionResult(ResultModel<VersionUpdateModel> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                if (res.getData() != null) {
                    VersionUpdateModel updateModel = res.getData();
                    int localVersionCode = BuildConfig.VERSION_CODE;
                    if (updateModel.getId() != null && !updateModel.getId().equals("")) {
                        downUrl = updateModel.getDownloadurl();
                        int serVersionCode = Integer.parseInt(updateModel.getVersioncode());
                        if (localVersionCode < serVersionCode) {
                            //有新版本
                            doNewVersionUpdate();
                        } else {
                            //没有新版本
                            notNewVersionDlgShow();
                        }
                    } else {
                        //没有新版本
                        notNewVersionDlgShow();
                    }

                }
            } else {
                TastyToast.makeText(this, res.getErrmsg(), app.SHORT, app.ERROR);
            }
        }
    }


    android.os.Handler handler = new android.os.Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            TastyToast.makeText(AboutActivity.this, "下载成功", app.SHORT, app.SUCCESS);
            //将下载进度对话框取消
            pBar.cancel();
            //安装apk，也可以进行静默安装
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "dccx_ck.apk")),
                    "application/vnd.android.package-archive");
            startActivityForResult(intent, 10);
        }
    };


    void doNewVersionUpdate() {
        new MaterialDialog.Builder(this)
                .title("提示")
                .titleGravity(GravityEnum.CENTER)
                .titleColorRes(R.color.colorFontGray)
                .content("发现新版本，确定升级吗？")
                .contentColorRes(R.color.colorFontGray)
                .positiveText("确定")
                .positiveColor(ContextCompat.getColor(this, R.color.colorFontBlue))
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                        if (Environment.getExternalStorageState().equals(
                                Environment.MEDIA_MOUNTED)) {
                            downFile();//点击确定将apk下载
                        } else {
                            TastyToast.makeText(AboutActivity.this, "SD卡不可用，请插入SD卡", app.SHORT, app.WARNING);
                        }
                    }
                })
                .negativeText("取消")
                .negativeColor(ContextCompat.getColor(this, R.color.colorFontGray))
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                    }
                })
                .buttonsGravity(GravityEnum.CENTER)
                .show();
    }

    void downFile() {
        pBar = new ProgressDialog(AboutActivity.this);
        pBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pBar.setCancelable(false);
        pBar.setTitle("正在下载...");
        pBar.setMessage("请稍候...");
        pBar.setProgress(0);
        pBar.show();
        new Thread() {
            public void run() {
                try {
                    URL url = new URL(downUrl);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    con.setReadTimeout(5000);
                    con.setConnectTimeout(5000);
                    con.setRequestProperty("Charset", "UTF-8");
                    con.setRequestMethod("GET");
                    if (con.getResponseCode() == 200) {
                        int length = con.getContentLength();// 获取文件大小
                        InputStream is = con.getInputStream();
                        pBar.setMax(length); // 设置进度条的总长度
                        FileOutputStream fileOutputStream = null;
                        if (is != null) {
                            //对apk进行保存
                            File file = new File(Environment.getExternalStorageDirectory()
                                    .getAbsolutePath(), "dccx_ck.apk");
                            fileOutputStream = new FileOutputStream(file);
                            byte[] buf = new byte[1024];
                            int ch;
                            int process = 0;
                            while ((ch = is.read(buf)) != -1) {
                                fileOutputStream.write(buf, 0, ch);
                                process += ch;
                                pBar.setProgress(process); // 实时更新进度了
                            }
                        }
                        if (fileOutputStream != null) {
                            fileOutputStream.flush();
                            fileOutputStream.close();
                        }
                        //apk下载完成，使用Handler()通知安装apk
                        handler.sendEmptyMessage(0);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }.start();
    }

    void notNewVersionDlgShow() {
        new MaterialDialog.Builder(this)
                .title("提示")
                .titleGravity(GravityEnum.CENTER)
                .titleColorRes(R.color.colorFontGray)
                .content("没有新版本！")
                .contentGravity(GravityEnum.CENTER)
                .contentColorRes(R.color.colorFontGray)
                .positiveText("确定")
                .positiveColor(ContextCompat.getColor(this, R.color.colorFontBlue))
                .buttonsGravity(GravityEnum.CENTER)
                .show();
    }

    @Click
    void re_hotline() {
        phone = txt_hotline.getText().toString().trim();
        callTelDialog(phone);
    }

    @Click
    void ly_bottom() {
        phone = txt_zhichi_tel.getText().toString().trim();
        callTelDialog(phone);
    }

    private void callTelDialog(String phone) {
        new MaterialDialog.Builder(this)
                .title("提示")
                .titleGravity(GravityEnum.CENTER)
                .titleColorRes(R.color.colorFontBigGray)
                .content("您确定要拨打" + " " + phone)
                .contentColorRes(R.color.colorFontBigGray)
                .positiveText("确定")
                .positiveColor(ContextCompat.getColor(this, R.color.colorFontBlue))
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        AndPermission.with(context)
                                .requestCode(100)
                                .permission(Manifest.permission.CALL_PHONE)
                                .callback(listener)
                                .rationale(new RationaleListener() {
                                    @Override
                                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                                        AndPermission.rationaleDialog(context, rationale).
                                                show();
                                    }
                                })
                                .start();
                    }
                })
                .negativeText("取消")
                .negativeColor(ContextCompat.getColor(this, R.color.colorFontGray))
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                    }
                })
                .buttonsGravity(GravityEnum.CENTER)
                .show();
    }

    private PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, List<String> grantedPermissions) {
            // 权限申请成功回调。
            if (requestCode == 100) {
                //打电话
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_CALL);
                intent.setData(Uri.parse("tel:" + phone));
                startActivity(intent);
            }
        }

        @Override
        public void onFailed(int requestCode, List<String> deniedPermissions) {
            // 权限申请失败回调。
            if (requestCode == 100) {
                TastyToast.makeText(context, "获取电话权限失败", TastyToast.LENGTH_SHORT, TastyToast.ERROR);
            }
        }
    };

    @Click
    void back_icon() {
        this.finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("AboutActivity"); //统计页面(仅有Activity的应用中SDK自动调用，不需要单独写。"SplashScreen"为页面名称，可自定义)
        MobclickAgent.onResume(this); //统计时长

    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("AboutActivity");
        MobclickAgent.onPause(this);
    }


}
